package org.hako.recite.word.parser.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.hako.recite.word.model.Word;
import org.hako.recite.word.parser.WordList;
import org.hako.recite.word.parser.WordListParseException;
import org.jopendocument.dom.spreadsheet.Sheet;
import org.jopendocument.dom.spreadsheet.SpreadSheet;

/**
 * Read words from open office spread sheet format. <br />
 * PS. This implement depends on {@code jOpenDocument}, and the use in practice
 * is slow. You'd better use Excel instead.
 * 
 * @since 0.4.5
 * @author <a href="mailto:xnnyygn@gmail.com">xnnyygn</a>
 */
public class OpenOfficeSpreadSheetWordListParser extends AbstractWordListParser {

	@Override
	public WordList parse(File file) throws WordListParseException {
		try {
			Sheet sheet = SpreadSheet.createFromFile(file).getSheet(0);
			int rowCount = sheet.getRowCount();
			int columnCount = sheet.getColumnCount();
			WordList wordList = new WordList();
			for (int row = 0; row < rowCount; row++) {
				String[] cells = new String[columnCount];
				for (int column = 0; column < columnCount; column++) {
					cells[column] = sheet.getCellAt(column, row).getTextValue();
				}
				if (row == 0) {
					wordList.setColumnTitles(cells);
				} else {
					wordList.addWord(new Word(cells));
				}
			}
			return wordList;
		} catch (IOException e) {
			throw new WordListParseException(e);
		}
	}

	@Override
	public WordList parse(InputStream inputStream)
			throws WordListParseException {
		throw new UnsupportedOperationException("Sorry, to parse "
				+ "open document spread sheet "
				+ "from input stream is not implemented.");
	}

}
